package Demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-07-30
 * Time: 19:47
 */
public class HashBucket {
    public static final int DEFAULT_CAPACITY = 10;//默认容量
    public Node[] array;
    public static final float LOAD_FACTOR = 0.75f;
    public int useSize;

    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public HashBucket(){
        this.array = new Node[DEFAULT_CAPACITY];
    }

    public void push(int key,int val){
        //求出下标
        int index = key % array.length;

        //遍历链表，判断是否有节点key值一样
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        //头插法
        Node newNode = new Node(key,val);
        newNode.next = array[index];
        array[index] = newNode;
        useSize++;

        //求负载因子
        float loadFactor = (useSize * 1.0f) / array.length;
        //判断数组是否需要扩容
        if(loadFactor > LOAD_FACTOR){
            Expansion();
        }
    }

    //扩容
    private void Expansion(){
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur =  array[i];
            while(cur != null){
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    //获取指定key对应的val值
    public int getVal(int key){
        int index = key % array.length;
        //遍历链表，判断是否有节点key值一样
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
